package com.qyhl.webtv.module_circle.circle.msg.action;

import android.os.Bundle;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.ContextUtilts;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.InteractionMessageBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 互动消息
 *
 * @author helin
 */
public class InteractionMessageFragment extends BaseFragment implements InteractionContract.InteractionView {
    @BindView(R2.id.interaction_message_list)
    RecyclerView mInteractionMessageList;
    @BindView(R2.id.interaction_message_refresh)
    SmartRefreshLayout mInteractionMessageRefresh;
    /**
     * 控制器
     */
    private InteractionPresenter mPresenter;
    /**
     * 最后一条消息ID
     */
    private int mLastId;
    /**
     * 数据
     */
    private List<InteractionMessageBean> mMessageList = new ArrayList<>();
    /**
     * adapter
     */
    private CommonAdapter<InteractionMessageBean> mInteractionListAdapter;


    @Override
    public void initImmersionBar() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static InteractionMessageFragment newInstance() {
        InteractionMessageFragment fragment = new InteractionMessageFragment();
        return fragment;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return  inflater.inflate(R.layout.circle_fragment_interaction_message, container, false);
    }

    @Override
    protected void create() {
        mPresenter = new InteractionPresenter(this);
        initView();
        mPresenter.getInteractionMessage(mLastId, 0);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        loadData();
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    /**
     * 初始化
     */
    private void initView() {
        mPresenter.clearMessageTip(0);
        mInteractionMessageRefresh.setEnableLoadMore(true);
        //刷新中禁止操作
        mInteractionMessageRefresh.setDisableContentWhenRefresh(true);
        mInteractionMessageRefresh.setRefreshHeader(new MaterialHeader(mContent));
        mInteractionMessageRefresh.setRefreshFooter(new ClassicsFooter(mContent));
        //下拉加载
        mInteractionMessageRefresh.setOnRefreshListener(refreshlayout -> {
            mLastId = 0;
            mPresenter.getInteractionMessage(mLastId, 0);
        });

        mInteractionMessageList.addItemDecoration(new RecycleViewDivider(
                this.getActivity(), LinearLayoutManager.HORIZONTAL, 1, ContextCompat.getColor(this.getContext(), R.color.global_gray_lv3)));
        mInteractionMessageList.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        //加载更多
        mInteractionMessageRefresh.setOnLoadMoreListener(refreshlayout -> {
            if (mMessageList.size() != 0) {
                mLastId = mMessageList.get(mMessageList.size() - 1).getId();
            }
            mPresenter.getInteractionMessage(mLastId, 1);
        });


        mInteractionMessageList.setAdapter(mInteractionListAdapter = new CommonAdapter<InteractionMessageBean>(this.getActivity(), R.layout.circle_item_circle_interaction, mMessageList) {
            @Override
            protected void convert(ViewHolder holder, final InteractionMessageBean interactionMessageBean, int position) {
                ImageView avatar = holder.getView(R.id.user_avatar);
                TextView content = holder.getView(R.id.interaction_content);
                TextView time = holder.getView(R.id.interaction_time);

                ImageView image = holder.getView(R.id.topic_image);
                TextView content2 = holder.getView(R.id.topic_content);
                ImageView videoIcon = holder.getView(R.id.topic_video_icon);

                image.setVisibility(View.GONE);
                content2.setVisibility(View.GONE);
                videoIcon.setVisibility(View.GONE);

                String string = DateUtils.mTranslateDate(interactionMessageBean.getGmtCreate());
                time.setText(string);
                Glide.with(InteractionMessageFragment.this)
                        .load(interactionMessageBean.getRelation().getLogo())
                        .apply(new RequestOptions().transform(new GlideCircleTransform(getContext())).error(R.drawable.comment_head_default))
                        .into(avatar);
                content.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                holder.setText(R.id.interaction_user_name, interactionMessageBean.getRelation().getNickName());
                switch (interactionMessageBean.getType()) {
                    case 1:
                        holder.setText(R.id.interaction_content, "关注了你");
                        break;
                    case 2: {
                        SpanUtils spanUtils = new SpanUtils(getContext());
                        if (!StringUtils.isEmpty(interactionMessageBean.getReply().getNickName())) {
                            spanUtils.append("回复").setSpans(new TextAppearanceSpan(ContextUtilts.getInstance().getmContext(), R.style.circle_comment_content));
                            spanUtils.append(" " + interactionMessageBean.getReply().getNickName() + " ").setSpans(new TextAppearanceSpan(ContextUtilts.getInstance().getmContext(), R.style.circle_comment_name)).setClickSpan(new ClickableSpan() {
                                @Override
                                public void onClick(View widget) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("dstusername", interactionMessageBean.getReply().getUsername());
                                    RouterManager.router(ARouterPathConstant.CIRCLE_USER,bundle);
                                }

                                @Override
                                public void updateDrawState(TextPaint ds) {
                                    //取消下划线
                                    ds.setUnderlineText(false);
                                }
                            });
                            spanUtils.append(": ").setSpans(new TextAppearanceSpan(ContextUtilts.getInstance().getmContext(), R.style.circle_comment_content));
                        }

                        spanUtils.append(interactionMessageBean.getMsg()).setSpans(new TextAppearanceSpan(ContextUtilts.getInstance().getmContext(), R.style.circle_comment_content));
                        content.setText(spanUtils.create());
                        //开始响应点击事件
                        content.setMovementMethod(LinkMovementMethod.getInstance());
                        content.setFocusable(false);
                        showContent(interactionMessageBean, image, content2, videoIcon);
                    }

                    break;
                    case 3: {
                        SpanUtils spanUtils = new SpanUtils(getContext());
                        spanUtils.append("回复").setSpans(new TextAppearanceSpan(ContextUtilts.getInstance().getmContext(), R.style.circle_comment_content));
                        spanUtils.append(" 我 ").setSpans(new TextAppearanceSpan(ContextUtilts.getInstance().getmContext(), R.style.circle_comment_name)).setClickSpan(new ClickableSpan() {
                            @Override
                            public void onClick(View widget) {
                                Bundle bundle = new Bundle();
                                bundle.putString("dstusername", interactionMessageBean.getReply().getUsername());
                                RouterManager.router(ARouterPathConstant.CIRCLE_USER,bundle);
                            }

                            @Override
                            public void updateDrawState(TextPaint ds) {
                                //取消下划线
                                ds.setUnderlineText(false);
                            }
                        });
                        spanUtils.append(": " + interactionMessageBean.getMsg()).setSpans(new TextAppearanceSpan(ContextUtilts.getInstance().getmContext(), R.style.circle_comment_content));
                        content.setText(spanUtils.create());
                        //开始响应点击事件
                        content.setMovementMethod(LinkMovementMethod.getInstance());
                        content.setFocusable(false);
                        showContent(interactionMessageBean, image, content2, videoIcon);
                    }

                    break;
                    case 4:
                        content.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.drawable.circle_praise_off), null, null, null);
                        content.setCompoundDrawablePadding(5);
                        holder.setText(R.id.interaction_content, "赞了你");
                        showContent(interactionMessageBean, image, content2, videoIcon);
                        break;
                    default:
                        break;
                }
            }
        });

        mInteractionListAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle1 = new Bundle();
                if (mMessageList.get(position).getType() == 1) {
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if(isLogin){
                                bundle1.putInt("type", 1);
                                RouterManager.router(ARouterPathConstant.USER_LIST,bundle1);
                            }else{
                                RouterManager.routerLogin(getActivity(),0);
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });
                } else {

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if(isLogin){
                                bundle1.putString("id", String.valueOf(mMessageList.get(position).getLinkId()));
                                RouterManager.router(ARouterPathConstant.CIRCLE_DETAIL,bundle1);
                            }else{
                                RouterManager.routerLogin(getActivity(),0);
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });
                }

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * 展示主题内容
     *
     * @param interactionMessageBean
     */
    private void showContent(InteractionMessageBean interactionMessageBean, ImageView image, TextView content, ImageView videoIcon) {
        //图片
        if (StringUtils.isNotEmpty(interactionMessageBean.getPic())) {
            image.setVisibility(View.VISIBLE);
            Glide.with(InteractionMessageFragment.this)
                    .load(interactionMessageBean.getPic())
                    .apply(new RequestOptions().error(R.drawable.mn_icon_load_fail))
                    .into(image);
            return;
        }
        //视频
        if (StringUtils.isNotEmpty(interactionMessageBean.getVideoThumb())) {
            image.setVisibility(View.VISIBLE);
            Glide.with(InteractionMessageFragment.this)
                    .load(interactionMessageBean.getVideoThumb())
                    .apply(new RequestOptions().error(R.drawable.mn_icon_load_fail))
                    .into(image);
            videoIcon.setVisibility(View.VISIBLE);
            return;
        }
        //文本
        content.setVisibility(View.VISIBLE);
        content.setText(interactionMessageBean.getContent());

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
        }
    }




    /**
     * 加载数据
     */
    private void loadData() {
        mInteractionMessageRefresh.autoRefresh();
    }

    @Override
    public void getMessageError() {
        mInteractionMessageRefresh.finishRefresh();
        mInteractionMessageRefresh.finishLoadMore();
        showToast("获取失败", ERROR);
    }

    @Override
    public void getMessageSuccess(List<InteractionMessageBean> data, int type) {
        mInteractionMessageRefresh.finishRefresh();
        mInteractionMessageRefresh.finishLoadMore();

        if (type == 0) {
            mMessageList.clear();
            mMessageList.addAll(data);
        } else {
            if (data.size() == 0) {
                showToast("暂无更多", INFO);
                return;
            }
            mMessageList.addAll(data);
        }
        mInteractionListAdapter.notifyDataSetChanged();
    }
}
